package com.wuliu.framework.interceptor;

import com.wuliu.common.utils.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 国际化拦截器
 *
 * @author realue
 * @version 1.0
 * @date 2023-10-13 17:08
 */
public class I18nInterceptor implements HandlerInterceptor {

    private static final String LANGUAGE_KEY = "language";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String language = request.getHeader(LANGUAGE_KEY);
        //默认中文
        Locale locale = new Locale("zh", "CN");
        if (StringUtils.isNotEmpty(language) && language.contains("-")) {
            locale = new Locale(language.split("-")[0], language.split("-")[1]);
        }
        LocaleContextHolder.setLocale(locale);
        return true;
    }

}
